package com.market.manage.service.impl;

import com.market.manage.mapper.AttRecMapper;
import com.market.manage.mapper.UsersMapper;
import com.market.manage.po.AttRec;
import com.market.manage.service.CheckService;
import com.market.po.Result;
import com.market.utils.Base64Utils;
import com.market.utils.FaceSpot;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class CheckServiceImpl implements CheckService {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private AttRecMapper attRecMapper;

    @Override
    public Result checkFace(Long userId, String base64, String status) {
//        String base64Str = base64.replace("data:image/jpeg;base64,", "");
        int index = base64.indexOf(',') + 1;
        String base64Str = base64.substring(index);
        String thumb = usersMapper.selThumbById(userId);
        String replace = thumb.replace('\\', '/');
        String userFace = Base64Utils.NetImageToBase64(replace);
        JSONObject jsonObject = FaceSpot.matchFace2(userFace, base64Str);
        Result result = new Result();
        try {
            double aDouble = jsonObject.getJSONObject("result").getDouble("score");
            if (aDouble > 80) {
                AttRec attRec = new AttRec();
                attRec.setAttTime(new Date());
                attRec.setUserid(userId);
                attRec.setStatus(status);
                Long count = attRecMapper.count(status);
                if (count == null || count == 0) {
                    //入库记录,只会记录每天的第一条考勤数据
                    int insert = attRecMapper.insert(attRec);
                    if (insert > 0) {
                        //对比通过
                        result.setStatus("1");
                    } else {
                        result.setStatus("0");
                    }
                }
            } else {
                result.setStatus("0");
            }
        } catch (Exception e) {
            result.setStatus("0");
            return result;
        }
        return result;
    }
}
